<template>
  <el-dialog
    title="实施清单详情"
    width="1200px"
    custom-class="gov-implement-list"
    :visible.sync="visible"
    :append-to-body="true"
    :close-on-click-modal="false"
    :before-close="handleClose"
  >
    <div class="content">
      <el-form ref="detailForm" :rules="detailRules" :model="detail" label-width="120px">
        <el-form-item label="实施清单名称" required prop="name">
          <el-input :disabled="handleType === 'scan'" v-model="detail.name" placeholder="实施清单名称"></el-input>
        </el-form-item>
      </el-form>
      <div class="implement-info">
        <table>
          <tr>
            <td>所属区划：</td>
            <!-- <td>{{ operList.length > 0 ? operList[0].name : '-' }}</td> -->
            <td>{{ catalog && areaMap[catalog.areaCode] ? areaMap[catalog.areaCode].value : '-' }}</td>
            <td>事项类型：</td>
            <td>{{ catalog ? eventTypeMap[catalog.typeId] : '-' }}</td>
            <td>基本编码：</td>
            <td>{{ catalog ? catalog.basicCoding : '-' }}</td>
          </tr>
          <tr>
            <td>事项名称：</td>
            <td>{{ catalog ? catalog.ecName : '-' }}</td>
            <td>行使层级：</td>
            <td>{{ catalog ? catalog.hierarchyNames : '-' }}</td>
            <td>设定依据：</td>
            <td>{{ catalog ? catalog.settingBasis : '-' }}</td>
          </tr>
        </table>
      </div>
      <div class="dynamic-form" v-loading="loading.form">
        <div class="form-type-list">
          <el-button
            v-for="item in formList"
            :key="item.eictId"
            type="primary"
            :disabled="!detail.eventId"
            :title="detail.eventId ? '' : '请先创建清单，可点击下一步'"
            @click="formChangeHandle(item)"
            round
            :plain="curForm.eictId !== item.eictId"
          >
            <span :class="{ error: !rules[item.eictCode] }">{{ item.eictName }}</span>
          </el-button>
        </div>
        <div class="form-content">
          <div v-for="item in formList" :key="item.eictCode">
            <!-- 受理条件 -->
            <acceptanceCondition
              :selected="dynamicFormValue[item.eictCode]"
              v-show="curForm.eictCode === item.eictCode"
              :handleType="handleType"
              v-if="item.eictCode === 'accept_condition'"
              :ref="item.eictCode"
            />
            <!-- 受理条件 -->
            <!-- 申请材料 -->
            <applicationMaterials
              v-show="curForm.eictCode === item.eictCode"
              :selected="dynamicFormValue[item.eictCode]"
              :ref="item.eictCode"
              :catalog="catalog"
              :handleType="handleType"
              v-else-if="item.eictCode === 'material'"
            />
            <!-- 申请材料 -->
            <!-- 常见问题 -->
            <commonProblem
              :selected="dynamicFormValue[item.eictCode]"
              v-show="curForm.eictCode === item.eictCode"
              :ref="item.eictCode"
              :handleType="handleType"
              v-else-if="item.eictCode === 'common_question'"
            />
            <!-- 常见问题 -->
            <!-- 办事地址 -->
            <handleAddress
              :ref="item.eictCode"
              :selected="dynamicFormValue[item.eictCode]"
              v-show="curForm.eictCode === item.eictCode"
              :handleType="handleType"
              v-else-if="item.eictCode === 'handle_address' && !loading.form"
            />
            <!-- 办事地址 -->
            <!-- 办理环节 -->
            <handleLink
              :ref="item.eictCode"
              :selected="dynamicFormValue[item.eictCode]"
              v-show="curForm.eictCode === item.eictCode"
              :handleType="handleType"
              v-else-if="item.eictCode === 'event_tache_limit_time'"
            />
            <!-- 办理环节 -->
            <!-- 动态表单 -->
            <dynamicForm
              v-show="curForm.eictCode === item.eictCode"
              v-else
              :formItemData="dynamicFormMap[item.eictCode]"
              :handleType="handleType"
              :formItemValue="dynamicFormValue.event_implementation_dynamic_character"
              :ref="item.eictCode"
            />
            <!-- 动态表单 -->
          </div>
        </div>
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" v-if="handleType !== 'scan' && this.detail.eventId" plain @click="prevHandle">
        上一步
      </el-button>
      <el-button type="info" plain @click="handleClose">取消</el-button>
      <!-- 只有暂存状态才能暂存 -->
      <el-button
        type="primary"
        :loading="loading.form"
        v-if="handleType !== 'scan'"
        plain
        @click="draftHandle"
        :disabled="selectItem && selectItem.state !== 'D'"
      >
        暂存
      </el-button>
      <!-- 状态为待审核得不能再次提交审核 selectItem && selectItem.state === 'Y' && isApproval 才能提交审核-->
      <el-button
        type="primary"
        :loading="loading.form"
        v-if="handleType !== 'scan'"
        @click="submit"
        :disabled="!(selectItem && selectItem.state === 'Y')"
      >
        提交审核
      </el-button>
      <el-button v-if="handleType !== 'scan' && this.detail.eventId" type="primary" plain @click="nextHandle">
        下一步
      </el-button>
    </span>
    <!-- 实施清单提交审核 -->
    <implementListCheck
      :visible.sync="checkVisible"
      :checkChangeList="checkChangeList"
      :checkData="selectItem"
      @success="handleClose"
    />
    <!-- 实施清单提交审核 -->
  </el-dialog>
</template>

<script>
  import axios from 'axios';
  import dynamicForm from '../dynamicForm';
  import implementListCheck from '@/components/implementListCheck';
  import acceptanceCondition from './acceptanceCondition';
  import applicationMaterials from './applicationMaterials';
  import commonProblem from './commonProblem';
  import handleAddress from './handleAddress';
  import handleLink from './handleLink';
  export default {
    components: {
      dynamicForm,
      acceptanceCondition,
      applicationMaterials,
      commonProblem,
      handleAddress,
      handleLink,
      implementListCheck
    },
    props: {
      visible: {
        type: Boolean
      },
      // clone克隆、edit编辑、scan查看
      handleType: {
        type: String
      },
      selectItem: {
        type: Object,
        default: () => {
          return {};
        }
      },
      // 父级信息
      parentObj: {
        type: Object,
        default: () => {
          return {};
        }
      },
      eicTemplet: {
        type: Number,
        default: () => {
          return 1;
        }
      },
      areaCode: {
        type: String
      },
      exerciseHierarchyMap: Object,
      eventTypeMap: Object,
      operList: Array,
      areaMap: Object
    },
    data() {
      return {
        // 动态表单字段，formCode -> itemList
        dynamicFormMap: {},
        // 动态表单所有字段的值，formCode -> itemValue
        dynamicFormValue: {},
        // 动态表单列表
        formList: [],
        // 当前操作表单
        curForm: {},
        // 验证结果
        rules: {},
        // 动态表单
        dynamicFormStr: [
          'event_implementation_dynamic_character',
          'event_implementation',
          'approval_result_type',
          'ec_extended_information',
          'handle_workflow',
          'fee_set'
        ],
        detail: {
          eventId: '',
          name: ''
        },
        detailRules: {
          name: [{ required: true, message: '实施清单名称', trigger: 'blur' }]
        },
        loading: {
          form: false
        },
        // 提交审核弹窗
        checkVisible: false,
        // 审核改变项
        checkChangeList: [],
        // 字段缓存
        cacheField: {
          1: false,
          2: false
        },
        catalog: {}
      };
    },
    watch: {
      visible: {
        async handler(val) {
          if (val) {
            const { data } = await axios.request({
              url: `/api/v1/event/catalogue/${this.parentObj.ecId}`,
              method: 'get'
            });
            if (data.success && data.result) {
              this.catalog = data.result;
              this.catalog.hierarchyNames = this.catalog.hierarchyId
                .map((e) => {
                  return this.exerciseHierarchyMap[e];
                })
                .join(',');
            }

            const cache = this.cacheField[this.eicTemplet];
            if (!cache) {
              this.getAllFormList();
            } else {
              this.dynamicFormMap = cache;
            }

            if (this.selectItem && this.selectItem.id) {
              this.loading.form = true;
              this.getDetail();
            }
          } else {
            this.curForm = this.formList[0];
            // 清楚表单内容字段验证
            this.formList.forEach((e) => {
              if (this.$refs[e.eictCode][0].resetField) {
                this.$refs[e.eictCode][0].resetField();
              }
            });
            // 清楚表单验证
            for (let key in this.rules) {
              this.rules[key] = true;
            }
            // 清除清单详情表单
            this.$refs['detailForm'].resetFields();
            this.detail.eventId = '';

            this.catalog = {};
          }
        }
      }
    },
    computed: {},
    methods: {
      handleClose() {
        this.$emit('update:visible', false);
      },
      // 提交并审核
      submit() {
        this.$refs['detailForm'].validate(async (valid) => {
          if (valid) {
            const formData = {};
            let formValid = true;
            // 设置每个表单的值
            this.formList.forEach((e) => {
              const { eictCode } = e;
              let obj = this.$refs[eictCode][0].getFormData(true);
              const { data } = obj;
              if (JSON.stringify(data) !== '{}') {
                formData[eictCode] = data;
              }

              if (!obj.valid) {
                formValid = false;
              }

              this.rules[eictCode] = obj.valid;
            });

            if (formValid) {
              // 提交数据
              this.submitRequestHandle(formData);
            } else {
              this.$message.error('请检查标红的字段，并按照要求填写完整');
            }
          }
        });
      },
      async submitRequestHandle(formData) {
        this.loading.form = true;
        let { name, eventId } = this.detail;
        let { parentEventId, newEcId } = this.getParentIDAndEcId();

        const { areaCode, deptId } = this.catalog;

        const { data } = await axios.request({
          url: '/api/v1/event/implementation/getChangeItems',
          method: 'post',
          data: {
            formData,
            implementName: name,
            eventId,
            parentEventId,
            ecId: newEcId,
            areaCode,
            deptId
          }
        });
        this.loading.form = false;
        if (data.success) {
          this.checkVisible = true;
          this.checkChangeList = data.result || [];
        }
      },
      // 暂存
      async draftHandle() {
        this.$refs['detailForm'].validate(async (valid) => {
          if (valid) {
            this.loading.form = true;

            const formData = {};

            // 设置每个表单的值
            this.formList.forEach((e) => {
              const { eictCode } = e;
              let obj = this.$refs[eictCode][0].getFormData(false);
              const { data } = obj;
              if (JSON.stringify(data) !== '{}') {
                formData[eictCode] = data;
              }
            });

            let { name, eventId } = this.detail;

            // 克隆
            if (this.handleType === 'clone') {
              eventId = '';
            }

            let { parentEventId, newEcId } = this.getParentIDAndEcId();

            const { areaCode, deptId, typeId } = this.catalog;

            const { data } = await axios.request({
              url: '/api/v1/event/implementation/draft',
              method: 'post',
              data: {
                formData,
                implementName: name,
                eventId,
                areaCode,
                deptId,
                parentEventId,
                eventType: typeId,
                ecId: newEcId
              }
            });
            this.loading.form = false;
            this.$emit('success');

            // 清空表单验证信息
            this.resetFromRules();

            if (data.success) {
              this.detail.eventId = data.result.eventId;
              this.$message.success('暂存成功');
            }
          } else {
            this.$message.error('请填写实施清单名称');
          }
        });
      },
      // 清空表单验证信息
      resetFromRules() {
        for (let key in this.rules) {
          this.rules[key] = true;
        }
      },
      getParentIDAndEcId() {
        const { id: parentId, type: parentType, ecId } = this.parentObj;
        let parentEventId = '';
        let newEcId = '';
        if (parentType === 'CATALOGUE_ITEM' || parentType === 'CATALOGUE_MAIN') {
          // 目录，只能创建清单主项
          parentEventId = '';
          newEcId = parentId;
        } else if (parentType === 'EVENT_MAIN') {
          // 实施清单主项下面只能创建实施清单子项
          parentEventId = parentId;
          newEcId = ecId;
        }

        return {
          parentEventId,
          newEcId
        };
      },
      // 获取所有表单列表
      async getAllFormList() {
        const { data } = await axios.get('/api/v1/event/implementation-character-type/list');
        if (data.code === 200) {
          const list = data.result || [];
          this.formList = list;
          this.curForm = this.formList[0];

          this.formList.forEach((form) => {
            // 动态表单需要获取数据
            if (this.dynamicFormStr.indexOf(form.eictCode) > -1) {
              this.getFieldByFromId(form, this.dynamicFormStr.length);
            }
            // 动态生成验证情况
            this.$set(this.rules, form.eictCode, true);
          });
        }
      },
      // 获取表单字段
      async getFieldByFromId(form, len) {
        const { data } = await axios.request({
          url: `/api/v1/event/implementation-character/list/type/${form.eictId}`,
          method: 'get',
          params: {
            eicTemplet: this.eicTemplet
          }
        });
        if (data.code === 200) {
          this.cacheField[this.eicTemplet] = this.dynamicFormMap;
          this.$set(this.dynamicFormMap, form.eictCode, data.result);
        }
      },
      // 表单切换
      formChangeHandle(item) {
        this.curForm = item;
      },
      // 上一步
      prevHandle() {
        let index = this.formList.findIndex((e) => {
          return e.eictId === this.curForm.eictId;
        });
        index = index === 0 ? 0 : index - 1;
        this.curForm = this.formList[index];
      },
      // 下一步
      nextHandle() {
        if (this.detail.name) {
          let index = this.formList.findIndex((e) => {
            return e.eictId === this.curForm.eictId;
          });
          const formLen = this.formList.length;
          index = index === formLen - 1 ? formLen - 1 : index + 1;
          this.curForm = this.formList[index];
        }

        //this.draftHandle();
      },
      // 获取清单详情
      async getDetail() {
        const { data } = await axios.request({
          url: `/api/v1/event/implementation/data/${this.selectItem.id}`,
          method: 'get'
        });
        if (data.success) {
          const { result } = data;
          const { formData, implementName, eventId, ecId } = result;
          this.detail.eventId = eventId;
          this.detail.name = implementName;
          for (let key in formData) {
            this.$set(this.dynamicFormValue, key, formData[key]);
          }

          if (!this.catalog.ecId) {
            const res = await axios.request({
              url: `/api/v1/event/catalogue/${ecId}`,
              method: 'get'
            });
            if (res.data.success) {
              this.catalog = res.data.result;
              this.catalog.hierarchyNames = this.catalog.hierarchyId
                .map((e) => {
                  return this.exerciseHierarchyMap[e];
                })
                .join(',');
            }
          }

          this.loading.form = false;
        }
      }
      // 创建清单Id
      // async createEventId() {
      //   const { data } = await axios.request({
      //     url: `/api/v1/event/implementation/id`,
      //     method: 'get'
      //   });
      //   this.loading.form = false;
      //   if (data.success) {
      //     this.detail.eventId = data.result;
      //   }
      // }
    },
    created() {},
    mounted() {
      this.getAllFormList();
    }
  };
</script>
<style lang="scss">
  .gov-implement-list {
    .el-dialog__body {
      .content {
        .implement-info {
          margin-bottom: 20px;
          table {
            width: 100%;
            border-left: 1px solid #e4e4e4;
            border-top: 1px solid #e4e4e4;
            border-collapse: collapse;
            tr > td {
              padding: 10px 0;
              border-right: 1px solid #e4e4e4;
              border-bottom: 1px solid #e4e4e4;
              width: 15%;
              &:nth-child(2n + 1) {
                background-color: #ebf0f5;
                text-align: right;
                padding-right: 10px;
              }
              &:nth-child(2n) {
                text-align: left;
                padding-left: 10px;
              }
            }
          }
        }
        .dynamic-form {
          display: flex;
          height: 600px;
          .form-type-list {
            width: 100px;
            margin-right: 20px;
            .el-button {
              margin-bottom: 10px;
              margin-left: 0;
              .error {
                color: red;
              }
            }
          }
          .form-content {
            flex: 1;
            overflow-y: auto;
          }
        }
      }
    }
    .el-dialog__footer {
      text-align: center;
    }
  }
</style>
